//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.ctrip.corp.obt.shard.utils;

import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;

import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Properties Wrapper
 */
public class PropertiesWrapper {

    private final Properties delegate;

    public static PropertiesWrapper newInstance(Properties properties) {
        return new PropertiesWrapper(properties);
    }

    private Set<String> keys() {
        return this.delegate.stringPropertyNames();
    }

    public PropertiesWrapper whenNotBlank(String key, Consumer<String> consumer) {
        String value = this.delegate.getProperty(key);
        if (StringUtils.isNotBlank(value)) {
            consumer.accept(value);
        }

        return this;
    }

    public <T> PropertiesWrapper whenNotBlank(String key, Function<String, T> function, Consumer<T> consumer) {
        String value = this.delegate.getProperty(key);
        if (StringUtils.isNotBlank(value)) {
            consumer.accept(function.apply(value));
        }

        return this;
    }

    public Map<String, Properties> group(String group) {
        Set<String> keys = this.keys();
        Set<String> inner = keys.stream().filter((i) -> i.startsWith(group)).collect(Collectors.toSet());
        if (CollectionUtils.isEmpty(inner)) {
            return Collections.emptyMap();
        } else {
            Map<String, Properties> map = CollectionUtils.newHashMap();
            inner.forEach((i) -> {
                Properties p = new Properties();
                String key = i.substring(group.length()) + ":";
                int keyIndex = key.length();
                keys.stream()
                        .filter((j) -> j.startsWith(key))
                        .forEach((j) -> p.setProperty(j.substring(keyIndex), this.delegate.getProperty(j)));
                map.put(this.delegate.getProperty(i), p);
            });
            return map;
        }
    }

    private PropertiesWrapper(final Properties delegate) {
        this.delegate = delegate;
    }
}
